<template>
  <div>
    <div class="container">
      <Breadcrumb />
      <a-card class="data-card">
        <a-row>
          <a-col :flex="1">
            <a-form
              :model="formModel"
              :label-col-props="{ span: 6 }"
              :wrapper-col-props="{ span: 18 }"
            >
              <a-row :gutter="20">
                <a-col :span="5">
                  <a-form-item field="nickname" label="姓名">
                    <a-input
                      v-model="formModel.nickname"
                      placeholder="请输入姓名"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-form-item field="patientSex" label="性别">
                    <a-select
                      v-model="formModel.sex"
                      :options="sexs"
                      placeholder="请选择性别"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="groupNamezh" label="组织">
                    <a-cascader
                      v-model="formModel.deptId"
                      check-strictly
                      :options="organizations"
                      placeholder="请选择所在组织"
                      :field-names="organizationsFields"
                      :show-all-levels="false"
                      @change="changsd"
                      allow-clear
                    ></a-cascader>
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-space :size="18">
                    <a-button type="primary" @click="onPageChange(1)">
                      <template #icon>
                        <icon-search />
                      </template>
                      搜索
                    </a-button>
                    <a-button @click="reset">
                      <template #icon>
                        <icon-refresh />
                      </template>
                      重置
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
        <a-divider style="margin-top: 0" />

        <a-table
          ref="userList"
          row-key="userId"
          v-model:selectedKeys="userIds"
          :loading="loading"
          page-position="bottom"
          :pagination="pagination"
          :row-selection="rowSelection"
          :columns="columns"
          :data="renderData"
          :bordered="false"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #sex="{ record }">
            <template v-for="(item, index) in sexs">
              <span v-if="record.sex == item.value">{{ item.label }}</span>
            </template>
          </template>
          <template #groupName="{ record }">
            {{ record.groupName }}-{{ record.attribute }}
          </template>

          <template #option="{ record }">
            <a-space :size="18">
              <div @click="openEdit(record)" class="zdivbot">分配治疗师</div>
            </a-space>
          </template>
        </a-table>
      </a-card>
    </div>
    <!-- 分配治疗师 -->
    <!--  -->
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancels"
      :on-before-ok="handleChecks"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 治疗项目</template>
      <div class="hzbox">
        <div>患者姓名:{{ addForm.nickname }}</div>
        <div>身份证号:{{ addForm.idCard }}</div>
        <div>患者年龄:{{ addForm.age }}</div>
        <div>患者性别:{{ addForm.sex == 'F' ? '女' : '男' }}</div>
        <div>接待部门:{{ addForm.groupName }}-{{ addForm.attribute }}</div>
      </div>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-form-item field="startTime" label="开始日期">
          <a-date-picker
            show-time
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:00"
            v-model="addForm.startTime"
            :hide-disabled-options="false"
            :disabledTime="disabledTime"
            @change="getendtime"
            :disabledDate="disabledDate"
          />
        </a-form-item>
        <a-form-item field="endTime" label="结束日期">
          <a-date-picker
            show-time
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:00"
            v-model="addForm.endTime"
            :disabledTime="disabledTime"
            :disabled="true"
          />
        </a-form-item>
        <a-form-item field="therapistId" label="治疗师">
          <a-select
            v-model="addForm.therapistId"
            :options="therapistIddata"
            :field-names="fieldNames"
            placeholder="请选择"
            allow-clear
            allow-search
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts">
  export default {
    name: 'user',
  };
</script>
<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import useLoading from '@/hooks/loading';
  import { useSelectionStore } from '@/store';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message, Modal } from '@arco-design/web-vue';
  import {
    patientTreatmentWaitList,
    therapistList,
    assignTherapist,
  } from '@/api/patient.ts';

  import { getTimeConf } from '@/api/therapist.ts';
  //   import { deptTree } from '@/api/dept.ts';
  import { organizationTree } from '@/api/organization.ts';
  const { loading, setLoading } = useLoading(true);
  //   import { majorTree } from '@/api/major.ts';
  //   分配治疗师
  const addModel = ref();
  const handleChecks = (done) => {
    console.log('执行了', addForm.value);

    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          assignTherapist(addForm.value).then((res) => {
            if (res.code == '200') {
              Message.success({
                content: res.message,
              });
              done(true);
              fetchData();
              addForm.value = [];
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const therapistIddata = ref([]);
  const openEdit = (item) => {
    addForm.value = item;
    console.log('tiem', item);
    addShow.value = true;
    therapistList({
      groupName: addForm.value.groupNameId,
      attribute: addForm.value.attributeId,
    }).then((res) => {
      if (res.code == 200) {
        therapistIddata.value = res.data;
      }
    });
  };
  const handleCancels = () => {
    addForm.value = [];
    addShow.value = false;
  };
  const addForm = ref([]);
  const changsd = (value) => {
    formModel.value.groupName = '';
    formModel.value.attribute = '';
    function findParentIdById(idToFind) {
      for (let i = 0; i < organizations.value.length; i++) {
        const item = organizations.value[i];
        if (item.id === idToFind) {
          return item.parentId;
        }
        if (item.children) {
          for (let j = 0; j < item.children.length; j++) {
            const childItem = item.children[j];
            if (childItem.id === idToFind) {
              return item.id;
            }
            if (childItem.children) {
              for (let k = 0; k < childItem.children.length; k++) {
                const grandChildItem = childItem.children[k];
                if (grandChildItem.id === idToFind) {
                  return childItem.id;
                }
              }
            }
          }
        }
      }
      return null;
    }
    const parentId = findParentIdById(value);

    formModel.value.attribute = value;
    formModel.value.groupName = parentId;
    if (parentId == 0) {
      formModel.value.attribute = '';
      formModel.value.groupName = value;
    }
  };
  const rules = {
    startTime: [
      {
        required: true,
        message: '请选择开始日期',
      },
    ],
    endTime: [
      {
        required: true,
        message: '请选择结束日期',
      },
    ],
    therapistId: [
      {
        required: true,
        message: '请选择治疗师',
      },
    ],
  };
  const fieldNames = { value: 'therapistId', label: 'nickname' };
  const addFormzlxm = ref({
    groupNamezh: '',
    groupName: '',
    attribute: '',
    startTime: '',
    patientId: '',
  });

  const addShow = ref(false);
  const addShows = ref(false);

  const userIds = ref([]);

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '患者姓名',
      dataIndex: 'nickname',
    },
    {
      title: '患者身份证',
      dataIndex: 'idCard',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      slotName: 'sex',
      align: 'center',
    },
    {
      title: '年龄',
      dataIndex: 'age',
    },
    {
      title: '接待部门',
      dataIndex: 'groupName',
      slotName: 'groupName',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      slotName: 'remark',
    },
    {
      title: '安排治疗',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);

  const sexs = useSelectionStore().sexs;

  const treatments = ref([
    {
      value: 'true',
      label: '是',
    },
    {
      value: 'false',
      label: '否',
    },
  ]);
  const generateFormModel = () => {
    return {
      patientName: '',
      patientSex: '',
      treatment: '',
    };
  };

  const formModel = ref(generateFormModel());
  const renderData = ref([]);
  const userList = ref();

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  // 定义时间配置类型
  interface TimeConf {
    confKey: string;
    confValue: string;
  }

  const timedata = ref<TimeConf[]>([]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      patientTreatmentWaitList(data).then((res) => {
        let list = res.data.list || [];
        renderData.value = list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;
        userList.value.selectAll(false);
      });

      getTimeConf().then((res) => {
        if (res.code == 200) {
          timedata.value = res.data;
          console.log('获取当前工作时间', timedata.value);
        }
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };

  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };
  fetchData();

  const organizations = ref([]);

  const getOrganizations = () => {
    organizationTree().then((res) => {
      organizations.value = res.data || [];
    });
  };
  getOrganizations();
  const organizationsFields = {
    value: 'id',
    label: 'name',
  };

  // 修正 disabledTime 用法，参数 current: Date
  const disabledTime = (current: Date) => {
    // 获取工作时间配置
    const workTimeConf = timedata.value.find(
      (item) => item.confKey === 'work_time'
    );
    // 获取休息时间配置
    const restTimeConf = timedata.value.find(
      (item) => item.confKey === 'rest_time'
    );

    // 允许的小时（只根据工作时间，不再过滤休息时间段）
    let allowedHours: number[] = [];
    let endHour = 23;
    let endMinute = 0;
    if (workTimeConf) {
      const [start, end] = workTimeConf.confValue.split('-');
      const startHour = parseInt(start.split(':')[0], 10);
      endHour = parseInt(end.split(':')[0], 10);
      endMinute = parseInt(end.split(':')[1], 10);
      for (let h = startHour; h <= endHour; h++) {
        allowedHours.push(h);
      }
    }

    // 休息时间整点禁用小时（如 11:30-13:30，禁用12点小时）
    let restDisabledHours: number[] = [];
    if (restTimeConf) {
      const [restStart, restEnd] = restTimeConf.confValue.split('-');
      const restStartHour = parseInt(restStart.split(':')[0], 10);
      const restStartMinute = parseInt(restStart.split(':')[1], 10);
      const restEndHour = parseInt(restEnd.split(':')[0], 10);
      const restEndMinute = parseInt(restEnd.split(':')[1], 10);
      // 禁用被休息时间完全覆盖的整点小时
      for (let h = restStartHour + 1; h < restEndHour; h++) {
        restDisabledHours.push(h);
      }
      // 如果休息开始分钟为0，开始小时也整点禁用
      if (restStartMinute === 0) {
        restDisabledHours.push(restStartHour);
      }
      // 不需要处理结束小时本身
    }

    // 特殊处理：工作时间的结束小时（如16点）也要禁用（仅当结束分钟为0时）
    if (workTimeConf && endMinute === 0) {
      restDisabledHours.push(endHour);
    }

    // 禁用小时（只禁用不在工作时间范围的小时和被休息时间完全覆盖的小时）
    const disabledHours = () => {
      return Array.from({ length: 24 }, (_, i) => i).filter(
        (h) => !allowedHours.includes(h) || restDisabledHours.includes(h)
      );
    };

    // 禁用分钟（所有小时只能选0和30，且0/30是否可选由休息区间和工作时间动态判断）
    const disabledMinutes = (selectedHour?: number) => {
      const allowedMinutes = [0, 30];
      let disabled: number[] = [];
      // 默认禁用所有非0/30
      for (let i = 0; i < 60; i++) {
        if (!allowedMinutes.includes(i)) disabled.push(i);
      }
      // 休息区间禁用
      if (restTimeConf && typeof selectedHour === 'number') {
        const [restStart, restEnd] = restTimeConf.confValue.split('-');
        const restStartHour = parseInt(restStart.split(':')[0], 10);
        const restStartMinute = parseInt(restStart.split(':')[1], 10);
        const restEndHour = parseInt(restEnd.split(':')[0], 10);
        const restEndMinute = parseInt(restEnd.split(':')[1], 10);
        // 检查0/30是否在休息区间内
        allowedMinutes.forEach((m) => {
          const t = selectedHour * 60 + m;
          const restStartT = restStartHour * 60 + restStartMinute;
          const restEndT = restEndHour * 60 + restEndMinute;
          if (t >= restStartT && t < restEndT) {
            disabled.push(m);
          }
        });
      }
      // 工作时间结束分钟特殊处理：如果是最后一小时，且 endMinute 不是0，则禁用30分
      if (
        workTimeConf &&
        typeof selectedHour === 'number' &&
        selectedHour === endHour &&
        endMinute !== 0
      ) {
        disabled.push(30);
      }
      // 只返回禁用的分钟
      return Array.from(new Set(disabled)).sort((a, b) => a - b);
    };

    // 禁用日期（工作日）
    // 这里不在 disabledTime 里处理，a-date-picker 有 disabledDate 属性

    return {
      disabledHours,
      disabledMinutes,
    };
  };

  // 在模板中 :disabledTime="disabledTime"
  // :disabledDate="disabledDate"，disabledDate 保持原有实现
  const disabledDate = (current: any) => {
    const workDayConf = timedata.value.find(
      (item) => item.confKey === 'work_day'
    );
    if (!workDayConf) return false;
    const allowedDays = workDayConf.confValue.split(',').map(Number);
    // getDay: 0=周日, 1=周一, ..., 6=周六
    let day = current.getDay();
    // 如果 allowedDays 用 1~7，且7代表周日，则转换
    day = day === 0 ? 7 : day;
    return !allowedDays.includes(day);
  };
  // 工具函数：格式化时间，秒永远为00
  function formatDateToMinute(date: Date | string) {
    const d = typeof date === 'string' ? new Date(date) : date;
    const pad = (n: number) => n.toString().padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(
      d.getDate()
    )} ${pad(d.getHours())}:${pad(d.getMinutes())}:00`;
  }
  const getendtime = () => {
    if (!addForm.value.startTime) return;
    // 格式化 startTime，秒永远为00
    addForm.value.startTime = formatDateToMinute(addForm.value.startTime);
    const start = new Date(addForm.value.startTime);
    start.setMinutes(start.getMinutes() + 30);
    addForm.value.endTime = formatDateToMinute(start);
    console.log(
      '当前时间',
      addForm.value.startTime,
      '结束时间',
      addForm.value.endTime
    );
  };
</script>
